package service

import (
	"encoding/json"

	assetapi "github.com/hyperledger/fabric-samples/asset-kx/chaincode-go/chaincode/asset/api"
	"github.com/hyperledger/fabric-samples/asset-kx/chaincode-go/chaincode/assetrule/api"
	ledgerapi "github.com/hyperledger/fabric-samples/asset-kx/chaincode-go/chaincode/ledger-api"
	"github.com/hyperledger/fabric-samples/asset-kx/chaincode-go/chaincode/support"
)



type SmartAssetRuleContract struct {
	AssetContract       assetapi.AssetContractApi        `inject:"AssetContractApi"`
	AssetRuleSupportApi assetruleapi.AssetRuleSupportApi `inject:"AssetRuleSupportApi"`
}

func (s *SmartAssetRuleContract) CreateOrUpdateAssetRule(ctx ledgerapi.TransactionContextInterface, assetRuleContent string) error {
	assetRule, err :=assetruleapi.Unmarshal([]byte(assetRuleContent))
	if err != nil {
		return err
	}

	db := ctx.GetStateDb()
	err = db.Add(assetRule)
	if err != nil {
		return err
	}

	err = db.SetEvent("CreateOrUpdateAssetRule", assetRule.AssetType + ":" + assetRule.RuleType)
	return err
}

func (s *SmartAssetRuleContract) ReadAssetRules(ctx ledgerapi.TransactionContextInterface, assetType, ruleType string) ([]*assetruleapi.AssetRule, error) {
	stub := ctx.GetStub()
	result, err := stub.GetStateByPartialCompositeKey(assetruleapi.AssetTypeRule, []string{assetType, ruleType})
	if err != nil {
		return nil, err
	}
	var assetRules []*assetruleapi.AssetRule
	err = support.ProcessStateQueryResult(result, func(key string, value []byte) error {
		assetRule := &assetruleapi.AssetRule{}
		err := json.Unmarshal(value, assetRule)
		if err != nil {
			return err
		}
		assetRules = append(assetRules, assetRule)
		return nil
	})
	if err != nil {
		return nil, err
	}
	return assetRules, nil
}
